import winreg

from PySide6 import QtCore, QtGui
from PySide6.QtCore import QPropertyAnimation, QEasingCurve, QParallelAnimationGroup, QPoint, Qt, QTimer
from PySide6.QtGui import QCursor, QMouseEvent
from PySide6.QtWidgets import QMainWindow, QLabel, QTabBar
from ui.ui_mainWindow import Ui_MainWindow
from ui.app_settings import Settings


class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.setupUi(self)
        # 1 修改标题
        # ///////////////////////////////////////////////////////////////
        self.setWindowTitle("生态大数据分析工具箱")
        self.resize(1000, 700)
        self.horizontalLayout_6.setContentsMargins(0, 0, 0, 0)  # 程序运行阶段，设置部分工具的边距，方便stackedWidget调节大小

        # 2 控件初始化
        # ///////////////////////////////////////////////////////////////
        self.stackedWidget_main.setCurrentWidget(self.page_batch_tools)
        self.leftMenuBox.setMinimumWidth(46)
        self.leftSettingsBox.setMinimumWidth(0)  # 设置工具栏的最小宽度0，隐藏

        # 3 变量初始化
        # ///////////////////////////////////////////////////////////////

        # 4 控件事件
        # ///////////////////////////////////////////////////////////////

        # 4.1 LEFT MENUS 左侧菜单
        self.pushButton_menu.clicked.connect(self.buttonClick)
        self.pushButton_batch_tools.clicked.connect(self.buttonClick)
        self.pushButton_DeepL.clicked.connect(lambda: self.stackedWidget_main.setCurrentWidget(self.page_DeepL))
        self.pushButton_global.clicked.connect(lambda: self.stackedWidget_main.setCurrentWidget(self.page_global))

        # 4.2开关设置面板
        self.pushButton_setting.clicked.connect(self.buttonClick)  # 设置面板
        self.pushButton_setting_hide.clicked.connect(self.buttonClick)  # 设置面板关闭按钮

        # 4.3自定义的窗口控制按钮事件 BUTTONS CLICK
        self.pushButton_maximizeRestore.clicked.connect(self.buttonClick)  # 最大化、恢复按钮
        self.pushButton_minimize.clicked.connect(self.buttonClick)  # 最小化按钮
        self.pushButton_close.clicked.connect(self.buttonClick)  # 关闭按钮

        # 5 窗口无边框，可自定义缩放相关参数设定
        # ///////////////////////////////////////////////////////////////
        # 鼠标拖拽缩放窗口的识别区域宽度
        self._padding = Settings.RESIZING_PADDING
        # 设置标题栏的高度，作为标题栏和双击标题栏最大化和恢复的识别区域范围
        self.titleHeight = Settings.TITLEHEIGHT
        # 隐藏系统默认框架
        self.setWindowFlags(Qt.FramelessWindowHint)
        # 一些鼠标状态
        self.is_mousePressed = False
        self.is_resizing = False
        self.resize_direction = 'right'
        # 一些功能启用状态
        self.support_resize = True  # 允许窗口缩放
        self.support_double_max = True  # 允许双击最大化
        self.timer_cursorUpdater = QTimer(self)   # 创建一个定时器，用于更新鼠标指针样式




    def buttonClick(self):
        """
        所有按钮点击事件
        """
        # GET BUTTON CLICKED
        btn = self.sender()
        btnName = btn.objectName()

        # 判断是哪个按钮被点击了
        if btnName == "pushButton_menu":  # 左侧菜单按钮
            self.toggleMenu(True)
            # UIFunctions.resetStyle(self, btnName)
        elif btnName == "pushButton_setting" or btnName == "pushButton_setting_hide":  # 设置按钮和关闭设置面板按钮
            self.toggleLeftBox(True)
        elif btnName == "pushButton_maximizeRestore":   # 最大化、恢复按钮
            self.change_window_size()
        elif btnName == "pushButton_minimize":  # 最小化按钮
            self.showMinimized()
        elif btnName == "pushButton_close":  # 关闭按钮
            self.close()
        elif btnName == "pushButton_batch_tools":  # 批量工具按钮
            self.stackedWidget_main.setCurrentWidget(self.page_batch_tools)
        else:
            pass

    def toggleLeftBox(self, enable):
        """
        开关左侧设置面板
        """
        if enable:
            # GET WIDTH
            width = self.leftSettingsBox.width()
            maxExtend = Settings.LEFT_BOX_WIDTH
            standard = 0

            # SET MAX WIDTH
            if width == 0:
                widthExtended = maxExtend

            else:
                widthExtended = standard

            # ANIMATION
            self.animation = QPropertyAnimation(self.leftSettingsBox, b"minimumWidth")
            self.animation.setDuration(Settings.TIME_ANIMATION)
            self.animation.setStartValue(width)
            self.animation.setEndValue(widthExtended)
            self.animation.setEasingCurve(QEasingCurve.InOutQuart)
            self.animation.start()

    def toggleMenu(self, enable):
        """
        开关菜单
        """
        if enable:
            # GET WIDTH
            width = self.leftMenuBox.width()
            maxExtend = Settings.MENU_WIDTH
            standard = Settings.MENU_STANDARD_WIDTH

            # SET MAX WIDTH
            if width == Settings.MENU_STANDARD_WIDTH:
                widthExtended = maxExtend
            else:
                widthExtended = standard

            # ANIMATION
            self.animation = QPropertyAnimation(self.leftMenuBox, b"minimumWidth")
            self.animation.setDuration(Settings.TIME_ANIMATION)
            self.animation.setStartValue(width)
            self.animation.setEndValue(widthExtended)
            self.animation.setEasingCurve(QEasingCurve.InOutQuart)
            self.animation.start()

    # 窗口相关事件
    # ///////////////////////////////////////////////////////////////



    # 窗口可自定义缩放, 以下重写窗口拖拽事件
    # ///////////////////////////////////////////////////////////////
    # def set_mouse_tracking(self):
    #     self.ui.frame.setMouseTracking(True)
    #     self.ui.centralwidget.setMouseTracking(True)
    #     self.setMouseTracking(True)  # / 设置widget鼠标跟踪

    def resizeEvent(self, QResizeEvent):
        # 获取有效识别区域
        self.right_l = self.width() - self._padding
        self.right_r = self.width() + 1
        self.bottom_u = self.height() - self._padding
        self.bottom_d = self.height() + 1
        # # 识别区域
        # print('x识别区间：', self.right_l, ',', self.right_r)
        # print('y识别区间：', self.bottom_u, ',', self.bottom_d)

    def get_mouse_pos_of_window(self) -> QPoint:
        global_pos = QCursor.pos()
        window_pos = self.mapFromGlobal(global_pos)
        return window_pos

    def get_mouse_global_pos(self) -> QPoint:
        return QCursor.pos()

    def check_pos_status(self):
        """
        获取鼠标相对于窗口的坐标，根据鼠标所处的位置返回鼠标的状态
        """
        pos: QPoint = self.get_mouse_pos_of_window()
        if pos.x() >= self.right_l and pos.x() < self.right_r:
            if pos.y() >= 0:
                if pos.y() <= self.bottom_u:
                    return pos, "right"  # 右边界
                elif pos.y() < self.bottom_d:
                    return pos, "corner"  # 右下角
        if pos.y() >= self.bottom_u and pos.y() < self.bottom_d:
            if pos.x() >= 0:
                if pos.x() <= self.right_l:
                    return pos, 'bottom'  # 下边界
        if pos.x() >= 0 and pos.x() <= self.right_l and pos.y() >= 0 and pos.y() <= self.titleHeight:
            return pos, 'title'
        return pos, False

    def start_cursorUpdater(self):
        """
        启动计时器更新鼠标样式
        """
        if self.timer_cursorUpdater:
            self.timer_cursorUpdater.timeout.connect(self.update_cursor)
            self.timer_cursorUpdater.start(100)  # 每隔1秒触发一次鼠标移动事件

    def stop_cursorUpdater(self):
        """
        停止计时器更新鼠标样式
        """
        if self.timer_cursorUpdater:
            self.timer_cursorUpdater.stop()

    def update_cursor(self):
        """
        根据鼠标坐标获取状态，设定鼠标样式
        """
        pos, status = self.check_pos_status()
        if status is False:
            self.setCursor(Qt.ArrowCursor)
        elif status == 'right':
            self.setCursor(Qt.SizeHorCursor)
        elif status == 'bottom':
            self.setCursor(Qt.SizeVerCursor)
        elif status == 'corner':
            self.setCursor(Qt.SizeFDiagCursor)
        else:
            self.setCursor(Qt.ArrowCursor)

    def change_window_size(self):
        """
        自定义窗口设置——放大缩小
        """
        if not self.isMaximized():
            self.showMaximized()
            self.pushButton_maximizeRestore.setIcon(QtGui.QIcon(u":/icons/minimize.png"))
            self.stop_cursorUpdater()
        elif self.isMaximized():
            self.showNormal()
            self.pushButton_maximizeRestore.setIcon(QtGui.QIcon(u":/icons/maximize.png"))
            self.start_cursorUpdater()
        return self.isMaximized()
    # # 和上面的函数功能一样，只是名字不同
    # def restore_or_maximize_window(self):
    #     if self.isMaximized():
    #         self.showNormal()
    #         self.pushButton_maximizeRestore.setIcon(QtGui.QIcon(u":/icons/maximize.png"))
    #     else:
    #         self.showMaximized()
    #         self.pushButton_maximizeRestore.setIcon(QtGui.QIcon(u":/icons/minimize.png"))

    def mousePressEvent(self, event: QMouseEvent):
        self.is_mousePressed = True
        self.mouse_pos = self.get_mouse_global_pos()

    def mouseReleaseEvent(self, event: QMouseEvent):
        self.is_mousePressed = False
        self.is_resizing = False

    def mouseDoubleClickEvent(self, *args, **kwargs):
        """
        检测标题栏的双击状态，切换最大化与正常窗口
        """
        if self.check_pos_status()[1] == 'title' and self.support_double_max:
            self.change_window_size()

    def mouseMoveEvent(self, event: QMouseEvent):
        if self.is_resizing:
            pos = self.get_mouse_pos_of_window()
            if self.resize_direction == 'right' and self.support_resize:
                self.resize(pos.x(), self.height())
            elif self.resize_direction == 'down' and self.support_resize:
                self.resize(self.width(), pos.y())
            elif self.resize_direction == 'right-down' and self.support_resize:
                self.resize(pos.x(), pos.y())
            elif self.resize_direction == 'move':
                current_pos = self.get_mouse_global_pos()
                self.move(self.pos() + current_pos - self.mouse_pos)
                self.mouse_pos = current_pos
        else:
            if self.is_mousePressed:
                pos, status = self.check_pos_status()
                if status is False:
                    self.is_resizing = False
                if status == 'right':
                    # self.resize(pos.x(), self.height())
                    self.is_resizing = True
                    self.resize_direction = 'right'
                elif status == 'bottom':
                    self.is_resizing = True
                    self.resize_direction = 'down'
                elif status == 'corner':
                    self.is_resizing = True
                    self.resize_direction = 'right-down'
                elif status == 'title':
                    self.is_resizing = True
                    self.resize_direction = 'move'

    def hideEvent(self, *args, **kwargs):
        self.stop_cursorUpdater()

    def showEvent(self, *args, **kwargs):
        if self.support_resize:
            self.start_cursorUpdater()

    # 其他函数事件
    # ///////////////////////////////////////////////////////////////
    def get_desktop(self):
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                             r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
        desktop = winreg.QueryValueEx(key, "Desktop")[0]
        # print(desktop)
        return desktop